<template>
  <div>
    <van-popup v-model="dialogVisible" position="bottom" :style="{ height: '100%' }" closeable @close="handleClose">
      <div class="amap-main">
        <div id="container" style="width: 100%"></div>
        <div class="search">
          <el-input v-model="searchString" class="search-input" clearable prefix-icon="el-icon-search"
            placeholder="请输入搜索地点名称">
          </el-input>
          <van-icon name="wap-nav" v-show="tips && searchString" @click="changeShowTips" />
        </div>
        <div v-show="tips && searchString && isShowTips" class="search-content">
          <div v-for="item of tips" :key="item.id" @click="clickPlaceSearch(item)" class="ml-10">
            <div class="mt-10 detail">{{ item.name }}</div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader"
import { localStore } from "@/utils/sessionStore"
const globalConfig = localStore.get("globalConfig") // 读取全局配置
export default {
  name: "amapPopup",
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    defaultLnglat: {},
  },
  data() {
    return {
      map: null,
      searchString: "",
      autoOptions: {
        input: "tipInput",
      },
      auto: null,
      marker: null,
      infoWindow: null,
      geocoder: null,
      lnglat: null,
      imgUrl: "",
      tips: [],
      isShowTips:false
    }
  },
  mounted() {
    console.log(this.dialogVisible, "dialogVisible")
    this.initMap()
  },
  watch: {
    searchString: {
      handler(val) {
        this.amapAuto(val)
      },
    },
  },
  computed: {
    //申请的Web端(JS API) key
    key() {
      if (globalConfig && globalConfig.amap) {
        return globalConfig.amap.key
      } else {
        return ""
      }
    },
    securityJsCode() {
      if (globalConfig && globalConfig.amap) {
        return globalConfig.amap.securityJsCode
      } else {
        return ""
      }
    },
    ahref() {
      if (this.lnglat) {
        const lng = this.lnglat.lng
        const lat = this.lnglat.lat
        return `https://ditu.amap.com/regeo?lng=${lng}&lat=${lat}&src=uriapi&innersrc=uriapi`
      } else {
        return ""
      }
    },
  },
  methods: {
    initMap() {
      window._AMapSecurityConfig = {
        securityJsCode: this.securityJsCode,
      }
      AMapLoader.load({
        key: this.key, // 申请好的Web端开发者Key，首次调用 load 时必填
        plugins: [
          "AMap.AutoComplete",
          "AMap.PlaceSearch",
          "AMap.Marker",
          "AMap.InfoWindow",
          "AMap.Pixel",
          "AMap.Geocoder",
        ], // 需要使用的的插件列表
        version: "2.0",
      })
        .then((AMap) => {
          this.map = new AMap.Map("container", {
            //设置地图容器id
            viewMode: "3D", //是否为3D地图模式
            zoom: 15, //初始化地图放大级别
            resizeEnable: true,
            zoomEnable: true, // 地图是否可缩放，默认值为true
            dragEnable: true, // 地图是否可通过鼠标拖拽平移，默认为true
            doubleClickZoom: true, // 地图是否可通过双击鼠标放大地图，默认为true
            // center: [121.49218, 31.23357],//地图中心位置 不设定center时，API 将根据用户 IP 自动匹配地图中心点到用户所在城市的中心
          })

          this.map.on("click", (e) => {
            this.lnglat = e.lnglat
            this.tomark()
            this.regeoCode()
            this.submitAmapData()
          })
          if (this.defaultLnglat) {
            //位置初始化回显
            const lng = this.defaultLnglat.split(",")[0]
            const lat = this.defaultLnglat.split(",")[1]
            this.lnglat = {
              lng: lng,
              lat: lat,
            }
            this.tomark()
            this.regeoCode()
          }
          this.$emit("openAmapInit", {
                amap:this.map,
                callback: (amap) => {
                  this.amap = amap;
                },
          })
        })
        .catch((e) => {
          console.log("地图加载失败", e)
        })
    },
    tomark() {
      this.pxoveMark()
      const lng = this.lnglat.lng
      const lat = this.lnglat.lat
      const position = [lng, lat]
      this.marker = new AMap.Marker({
        position: position, //位置
      })
      this.map.add(this.marker)
      // this.marker.on("click", () => {
      //   //绑定click事件=》打开弹窗
      //   this.infoWindow.open(this.map, this.marker.getPosition())
      // })
    },
    pxoveMark() {
      if (this.marker) {
        this.marker.setMap(null)
        this.marker = null
      }
    },
    //Geocoder逆地理编码
    regeoCode() {
      this.geocoder = new AMap.Geocoder({
        city: "010", //城市设为北京，默认：“全国”
        radius: 500, //范围，默认：500
      })
      const lng = this.lnglat.lng
      const lat = this.lnglat.lat
      const lnglats = [lng, lat]
      this.geocoder.getAddress(lnglats, (status, result) => {
        console.log(status, result, "----")
        try {
          if (status === "complete" && result.regeocode) {
            let address = result.regeocode.formattedAddress
            let building = result.regeocode.addressComponent.building || "位置"
            //打开弹窗
            let info = []
            info.push(
              `<div style="padding:7px 0px 0px 0px;"><h4>${building}</h4>`
            )
            info.push(`<p class='input-item'>地址 :${address}</p></div></div>`)
            const infoWindow = new AMap.InfoWindow({
              anchor: "top-left",
              content: info.join(""), //使用默认信息窗体框样式，显示信息内容
            })
            infoWindow.open(this.map, lnglats)
          } else {
            log.error("根据经纬度查询地址失败")
          }
        } catch (error) {
          console.error(error)
        }
      })
    },
    amapAuto(val) {
      AMap.plugin("AMap.AutoComplete", () => {
        const autoOptions = {
          city: "全国",
        }
        var autoComplete = new AMap.Autocomplete(autoOptions)
        autoComplete.search(val, (status, result) => {
        this.tips = result.tips
        this.isShowTips = true
        })
      })
    },
    clickPlaceSearch(item) {
      const lng = item.location.lng
      const lat = item.location.lat
      //设置中心点
      this.map.setCenter([lng, lat])
      //设置层级
      this.map.setZoomAndCenter(16, [lng, lat])
    },
    submitAmapData() {
      if (this.lnglat) {
      const lng = this.lnglat.lng
      const lat = this.lnglat.lat
      const lnglats = `${lng},${lat}`
      this.$emit("setLnglats", lnglats)
      }
      this.$emit("update:dialogVisible", false)

    },
    changeShowTips(){
        this.isShowTips =!this.isShowTips
    },
    handleClose() {
      if (this.lnglat) {
        const lng = this.lnglat.lng
        const lat = this.lnglat.lat
        const lnglats = `${lng},${lat}`
        this.$emit("setLnglats", lnglats)
      }
      this.$emit("update:dialogVisible", false)
    },
  },
}
</script>
<style lang="scss" scoped>
#container {
  height: 100%;
}

.amap-sug-result {
  z-index: 99999 !important;
}

.amap-main {
  width: 100%;
  height: 500px;
  position: relative;
}

.img {
  width: 300px;
  height: 300px;
}

.search {
  width: 220px;
  padding-right: 0 !important;
  position: absolute;
  top: 0;
  left: 0;
  height: 30px;
  background-color: #f5f7fa;

  .search-input {
    height: 30px;
    width: 200px;
  }
}

.search-content {
  text-align: left;
  position: absolute;
  height: 400px;
  width: 200px;
  top: 30px;
  left: 0;
  background: rgba(252, 253, 252, 0.8);

  .detail {
    overflow: hidden;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
    white-space: nowrap;
  }

}
</style>
